import Cookies from 'js-cookie'
import router from '@/router'
import { Message } from 'element-ui'
import loginApi from "@/api/lejv/login"
import asyncRouter from "@/router/asyncRouter"
import {resetRouter} from "@/router/index"
import {removeInfo,removeToken,setToken,setInfo} from '@/utils/auth'
import { getMenuId } from "@/utils/index"


const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  isFresh:true,
  groupList:[],
  roleList:[],
  menuList:[]
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  UPDATE_MENU: (state,list) =>{
    state.menuList = list
    state.isFresh = false
  },
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  //登陆获取菜单
  doLogin({ commit }, data){
    // console.log(routerLists,asyncRouter)
    return new Promise((resolve, reject) => {
      removeToken()
      removeInfo()
      loginApi.doLogin(data)
        .then(res=>{
          // console.log(this.asyncRouter)
          resolve(res)
          if(res.code == 0){
            // console.log(asyncRouter)
            let params =   "Bearer " + res.data.token
            let item = {username:data.username}
            setToken(params)
            setInfo(item)
          }else{
            // console.log(res);
            Message.error(res.msg)
            reject()
          }
        }).catch(res=>{
          reject(res)
        })
    })
  },
  //获取菜单(避免刷新后丢失)
  getMenu({ commit }){
    let routerLists = [].concat(asyncRouter)
    return new Promise((resolve,reject)=>{
      loginApi.getMenu()
      .then(res=>{
        // console.log(res);
        if(res.code == 0){
          let userMenu = [],menuId = [],menu = res.data.menus
          if(menu){
            // for(let i = 0;i<menu.length;i++){
            //   menuId.push(menu[i].node_id)
            //   if(menu[i].children.length != 0){
            //     for(let j = 0;j < menu[i].children.length;j++){
            //       menuId.push(menu[i].children[j].node_id)
            //     }
            //   }
            // }
            // console.log(menu);
            menuId = getMenuId(menu,[])
            console.log(menuId,routerLists);
            
            if(menuId.length != 0){
              for(let k = 0;k<menuId.length;k++){
                for(let m = 0;m<routerLists.length;m++){
                  if(routerLists[m].node_id == menuId[k]){
                    userMenu.push(routerLists[m])
                  }
                }
              }
              // console.log(asyncRouter,userMenu);
              userMenu.forEach((userMenuValue, index) => {  //循环找出二级菜单
                // console.log('---',userMenu, userMenuValue.children)
                if(userMenuValue.children){
                  let test = []
                  userMenuValue.children.forEach((childValue, index) => {
                    menuId.forEach((menuIdValue, index) => {
                      if (menuIdValue == childValue.node_id) {
                          test.push(childValue)
                      }
                    })
                  })
                  userMenuValue.children = test
                }
              })
            }
          }
          let routeArr = userMenu.concat(router.options.routes)
          commit("UPDATE_MENU",routeArr)
          // console.log(userMenu,routeArr);
          resetRouter() //动态添加路由前需重置路由,避免浏览器警告(路由名称重复)
          router.addRoutes(routeArr)
          resolve()
        }
      })
      .catch(res=>{
        reject()
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
